package io.shdxhl.simplerpc.code.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.shdxhl.simplerpc.code.netty.response.RpcResponse;
import io.shdxhl.simplerpc.code.utils.ProtostuffUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * Response 二次的编码器
 */
@Slf4j
public class RpcResponseEncoder extends MessageToMessageEncoder<RpcResponse> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, RpcResponse rpcResponse, List<Object> list) throws Exception {
        try {
            byte[] bytes = ProtostuffUtil.serialize(rpcResponse);
            ByteBuf buffer = channelHandlerContext.alloc().buffer(bytes.length);
            buffer.writeBytes(bytes);
            list.add(buffer);
        } catch (Exception e) {
            log.error("RpcResponseEncoder encode error, msg:{}", e);
            throw new RuntimeException(e);
        }
    }
}
